<?php

namespace App\Models\Product;

use App\Jobs\MLMJob;
use App\Models\BaseModel;
use App\Models\User\User;

class ProductPurchase extends BaseModel
{

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $guarded = [];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = ['updated_at', 'shipment'];
    protected $table = 'product_purchase';

    protected $dateFormat = 'U';

    /**
     * 关联商品数据
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function product(){
        return $this->belongsTo('App\Models\Product\Product', 'product_id', 'product_id')->where('category', 1);
    }

    /**
     * 新增商品购买记录
     * @param $user_id
     * @param $product_id
     * @param $address_id
     * @param $type
     * @param Product $product
     * @param User $user
     * @param int $order_id
     * @param int $status
     * @param int $shipping_status
     * @return mixed
     */
    public function add($user_id, $product_id, $address_id, $type,
                        Product $product, User $user, $order_id=0, $shipping_status=0, $status=0){
        $this->user_id = $user_id;
        $this->product_id = $product_id;
        $this->address_id = $address_id;
        $this->type = $type;
        $this->order_id = $order_id;
        $this->status = $status;
        $this->shipping_status = $shipping_status;
        $product = $product->find($product_id);
        $this->title = $product->title;
        $this->point = $product->point;
        $this->money = $product->money;
        $this->cover = $product->cover;
        $this->save();
        return $this->id;
    }


    /**
     * 获取已购买商品历史记录
     * @param $user_id
     * @param $page
     * @param $size
     * @return mixed
     */
    public function get($user_id, $page, $size){
        $data = [];
        $data['list'] = $this
//            ->rightJoin('products', function($join){
//                $join->on('products.product_id', '=', 'product_purchase.product_id')->where('products.category', 1);
//            })
            ->where('product_purchase.user_id',$user_id)
            ->where('product_purchase.status',1)
            ->orderBy('product_purchase.created_at', 'desc')
            ->forPage($page, $size+1)
            ->get()
            ->toArray();

        $data['next_page'] = $page + 1;
        $data['page_size'] = $size;

        return $this->after($data);
    }

}
